package com.xu.sso.server.controller;

import com.alibaba.fastjson.JSONObject;
import com.xu.sso.core.enums.ErrorMessage;
import com.xu.sso.core.exception.SSOException;
import com.xu.sso.core.utils.ExceptionUtil;
import com.xu.sso.server.model.request.OpenApiRequest;
import com.xu.sso.server.model.response.OpenApiResponse;
import com.xu.sso.server.service.ApiService;
import com.xu.sso.server.utils.SignUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.lang.reflect.InvocationTargetException;

@RestController
@Slf4j
public class ApiController extends BaseController {

    @Autowired
    private ApiService apiService;

    @RequestMapping("/openApi")
    public OpenApiResponse openApi(@RequestBody @Valid OpenApiRequest request, BindingResult bindingResult) throws SSOException {
        log.info(">>>>>>>>>>>>>>>ApiController.openApi request=={}", JSONObject.toJSONString(request));
        validParams(bindingResult);
        String key = apiService.findAppKey(request.getAppId());
        SignUtil.verifySign(request, key);
        try {
            OpenApiResponse response = (OpenApiResponse) apiService.getClass().getDeclaredMethod(request.getMethod(), OpenApiRequest.class).invoke(apiService, request);
            return SignUtil.sign(response, request, key);
        } catch (InvocationTargetException e) {
            throw (SSOException) e.getTargetException();
        } catch (SSOException e) {
            throw e;
        } catch (Exception e) {
            log.error(">>>>>>>>>>>>>>>>>ApiController.openApi error=={}", e);
            throw ExceptionUtil.createException(ErrorMessage.UnknowError);
        }
    }

}
